#include "d3d.h"


MyD3D::MyD3D()
{
	lpd3d				= NULL;
	lpd3ddevice		= NULL;
	lpVB				= NULL;
}

MyD3D::~MyD3D()
{
	ReleaseD3D();
}


HRESULT MyD3D::InitD3D(HWND hWnd)
{
	if (FAILED(lpd3d = Direct3DCreate9(D3D_SDK_VERSION)))
		return E_FAIL;
	
	D3DPRESENT_PARAMETERS 	d3dpp;

	ZeroMemory(&d3dpp, sizeof(d3dpp));
	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

	HRESULT		hRes;
	hRes = lpd3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, 
										  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                          &d3dpp, &lpd3ddevice);

   if (FAILED(hRes))
	   return E_FAIL;
	return S_OK;
}

// Init vertex Data
HRESULT	MyD3D::InitVB()
{
	MyVertex		vertices[4] = 
	{
		{ 250.0f, 150.0f, 1.0f, 1.0f, 0xffff0000, },
		{ 650.0f, 150.0f, 1.0f, 1.0f, 0xff00ff00, },
		{ 250.0f, 550.0f, 1.0f, 1.0f, 0xff00ffff, },
		{ 650.0f, 550.0f, 1.0f, 1.0f, 0xffff0000, }
	};

	if ( FAILED (lpd3ddevice->CreateVertexBuffer( 4 * sizeof(MyVertex), 0, D3DFVF_MYVERTEX,
													      D3DPOOL_DEFAULT, &lpVB, NULL)))
	{
		return E_FAIL;
	}

	VOID*			pVertices;
	if (FAILED (lpVB->Lock (0, sizeof(vertices), (void**)&pVertices, 0 )))
		return E_FAIL;
	memcpy (pVertices, vertices, sizeof(vertices));
	lpVB->Unlock();

	return S_OK;
}


// Rendering Func
HRESULT MyD3D::Render()
{
	if (!lpd3ddevice)
		return E_FAIL;

	lpd3ddevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 255), 1.0f, 0);
	
	lpd3ddevice->BeginScene();
	
	// rendering here
	lpd3ddevice->SetStreamSource(0, lpVB, 0, sizeof ( MyVertex ));
	lpd3ddevice->SetFVF (D3DFVF_MYVERTEX);
	lpd3ddevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2);
	
	lpd3ddevice->EndScene();
	
	lpd3ddevice->Present(NULL, NULL, NULL, NULL);

	return S_OK;
}

void	MyD3D::ReleaseD3D()
{
	if (lpd3d)
		lpd3d->Release();

	if (lpd3ddevice)
		lpd3ddevice->Release();

	if (lpVB)
		lpVB->Release();
}